const request = require('request');
const Iconv = require('iconv-lite');
const mongodbHandler = require('../manager/mongodbManager');
const logHandler = require('../component/logHandler');
const net = require('net');

module.exports = {

  /**
   * 
   */
  getStockTransactionDataList: () => {

    return new Promise((resolve, reject) => {

      const port = 8000;
      const hostname = '127.0.0.1';

      // 定义两个变量， 一个用来计数，一个用来保存客户端
      let clients = {};
      let clientName = 0;

      // 创建服务器
      const server = new net.createServer();
      let stockTransactionDataList = [];
      server.on('connection', (client) => {
        client.name = ++clientName; // 给每一个client起个名
        clients[client.name] = client; // 将client保存在clients
        client.on('data', function (msg) { //接收client发来的信息
          let data = msg.toString();
          // console.info(data);
          if (client.name <= 400) {
            stockTransactionDataList.push(data);
            console.log(`客户端${client.name}发来一个信息：${data}`);
          }
          if (client.name == 400) {
            // client.end();
            // server.close();
            resolve(stockTransactionDataList);
          }
        });

        client.on('error', function (e) { //监听客户端异常
          console.log('client error' + e);
          client.end();
        });

        client.on('close', function () {
          delete clients[client.name];
          console.log(`客户端${client.name}下线了`);
        });

      });

      server.listen(port, hostname, function () {
        console.log(`服务器运行在：http://${hostname}:${port}`);
      });

      /************************************************************************** */

      mongodbHandler.findAllDocument().then((allDocument) => {
        for (let i in allDocument) {
          let code = allDocument[i].code.toLowerCase();
          let url = 'http://hq.sinajs.cn/list=' + code;
          request({ url: url, encoding: null }, function (error, response, body) {
            if (!error && response.statusCode == httpStatusCode.OK) {
              let data = Iconv.decode(body, 'gb2312').toString();

              const socket = new net.Socket();
              const port = 8000;
              const hostname = '127.0.0.1';
              socket.setEncoding = 'UTF-8';

              socket.connect(port, hostname, function () {
                socket.write(data);
              });

              socket.on('data', function (msg) {
                console.log(msg);
              });

              socket.on('error', function (error) {
                console.log('error' + error);
              });

              socket.on('close', function () {
                console.log('服务器端下线了');
              });
            }
          });
        }
        // resolve(stockTransactionDataList);
      });
    });

    // let _this = this;
    // return new Promise((resolve, reject) => {

    //   const getStockTransactionData = (url) => {
    //     return new Promise((resolve, reject) => {
    //       request({ url: url, encoding: null }, (error, response, body) => {
    //         logger.info('2222222');
    //         if (!error && response.statusCode == httpStatusCode.OK) {
    //           let data = Iconv.decode(body, 'gb2312').toString();
    //           resolve(data);
    //         }
    //       });
    //     });
    //   };

    //   let that = _this;
    //   mongodbHandler.findAllDocument().then((result) => {
    //     let stockTransactionDataList = [];
    //     for (let i in result) {
    //       let code = result[i].code.toLowerCase();
    //       let url = 'http://hq.sinajs.cn/list=' + code;
    //       getStockTransactionData(url).then((result) => {
    //         logger.info('1111111111');
    //         stockTransactionDataList.push(result);
    //       });
    //     }
    //     resolve(stockTransactionDataList);
    //   });
    // });
  }
}